package com.sunshulin.tag;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import com.bhms.module.resources.dictionary.mapper.DictValues;

/**
 * 数据字典标签库
 * 
 * @author 孙树林
 * 
 */
public class DicTag extends GeneralTag {

	private static final long serialVersionUID = -4604616013209910988L;

	/** 字典类型 */
	private String type;
	/** select名称 */
	private String name;

	@SuppressWarnings("unchecked")
	@Override
	public int doStartTag() throws JspException {
		Map<String, List<DictValues>> maps = (Map<String, List<DictValues>>) pageContext.getServletContext().getAttribute("dict");
		try {
			List<DictValues> list = maps.get(type);
			JspWriter writer = pageContext.getOut();
			writer.write(createSelectTag(list));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_PAGE;
	}

	/**
	 * 创建select下拉框
	 * 
	 * @param list
	 * @return
	 */
	public String createSelectTag(List<DictValues> list) {
		StringBuilder sb = new StringBuilder("<select name='" + name + "'>");
		sb.append("<option value=''>请选择..</option>");

		String value = findValue(name) != null ? findValue(name).toString() : null;

		for (DictValues dv : list) {
			if (value != null && value.equals(dv.getD_name())) {
				sb.append("<option value='" + dv.getD_name() + "' selected='selected'>" + dv.getD_value() + "</option>");
			} else {				
				sb.append("<option value='" + dv.getD_name() + "'>" + dv.getD_value() + "</option>");
			}
		}

		sb.append("</select>");
		return sb.toString();
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
